from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options

from customLogger import CustomLogger

class NewsCaptureBase:
    def __init__(self,
                 chrome_driver_path='webdriver/chromedriver-win64/chromedriver.exe',
                 chrome_binary_path='webdriver/chrome-win64/chrome.exe',
                 socks5_proxy='192.168.30.42:11111'):

        # 在类属性中初始化CustomLogger类
        self.logger = CustomLogger('NewsCapture.log')

        self.chrome_driver_path = chrome_driver_path
        self.chrome_binary_path = chrome_binary_path
        self.socks5_proxy = socks5_proxy
        self.user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36 Edg/129.0.0.0'
        self.options = Options()
        self.initialize_options()

        self.service = Service(self.chrome_driver_path)
        self.initialize_browser()

    def initialize_options(self):
        #  options 参考文档：https://pyhost.cn/tutorial/4171.html
        self.options.binary_location = self.chrome_binary_path if self.chrome_binary_path else None

        self.options.add_argument(f'user-agent={self.user_agent}')
        # self.options.add_argument('proxy-server=socks5://192.168.30.42:11111')
        # self.options.add_argument("--proxy-server={}".format(proxy))

        # 设置Socks5代理（如果提供了的话）
        if self.socks5_proxy:
            proxy_host, proxy_port = self.socks5_proxy.split(':')
            # 这里我们不直接通过Selenium设置代理，而是通过系统层面的socket设置
            # 但在实际使用时，由于Selenium的WebDriver通常不允许直接通过系统代理设置进行连接，
            # 因此我们需要通过Chrome的命令行参数来设置代理。
            # 注意：这种方式需要确保你的Chrome和ChromeDriver支持通过命令行参数设置代理。
            self.options.add_argument(f'--proxy-server=socks5://{proxy_host}:{proxy_port}')

        self.options.add_argument('--disable-extensions')
        self.options.add_argument('--disable-default-apps')
        self.options.add_argument('--disable-component-extensions-with-background-pages')
        self.options.add_argument('--hide-scrollbars')
        self.options.add_argument('--no-default-browser-check')
        self.options.add_argument('--mute-audio')
        self.options.add_argument('--no-first-run')

        self.options.add_argument('--no-sandbox')
        self.options.add_argument('--disable-dev-shm-usage')
        # self.options.headless = True
        # self.options.add_argument('--headless')
        # self.options.add_argument('--headless=new')
        self.options.add_argument('--disable-gpu')

        self.options.add_argument('--ignore-certificate-errors')
        self.options.add_argument('--allow-insecure-localhost')
        self.options.add_argument('--start-maximized')
        self.options.add_argument('--window-size=1143,886')
        self.options.add_argument("blink-settings=imagesEnabled=false")
        self.options.add_experimental_option('excludeSwitches', ['enable-automation'])
        self.options.add_experimental_option('useAutomationExtension', False)

        self.options.add_argument('--disable-web-security')
        self.options.add_argument('--use-fake-ui-for-media-stream')
        self.options.add_argument('--use-fake-device-for-media-stream')

        self.options.add_argument('--disable-domain-reliability')
        self.options.add_argument('--deny-permission-prompts')
        self.options.add_argument('--disable-notifications')

    def initialize_browser(self):
        try:
            self.browser = webdriver.Chrome(service=self.service, options=self.options)
            self.browser.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
                "source": """
                    Object.defineProperty(navigator, 'webdriver', {
                      get: () => undefined
                    })
                  """
            })
            self.logger.log('info', f"Chrome version: {self.browser.capabilities['browserVersion']}")
            self.logger.log('info', f"ChromeDriver version: {self.browser.capabilities['chrome']}")
        except Exception as e:
            self.logger.log('error', f"Error initializing the browser: {e}")
